package com.jerry.walking.module.activityPath.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jerry.walking.R;
import com.jerry.walking.base.BaseActivity;
import com.jerry.walking.base.BaseApplication;
import com.jerry.walking.base.BaseViewHolder;
import com.jerry.walking.base.MyBaseAdapter;
import com.jerry.walking.constant.Urls;
import com.jerry.walking.module.activityPath.bean.PathSearch;
import com.jerry.walking.utils.OkHttpUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Yang on 2016/5/16.
 *
 *        路线搜索  搜索界面
 *
 */
public class SearchActivity extends BaseActivity {

    @BindView(R.id.et_search)
    EditText editText;

    @BindView(R.id.ll_search)
    LinearLayout linearLayout;
    @BindView(R.id.gv_search)
    GridView gridView;

    @BindView(R.id.ll_search1)
    LinearLayout linearLayout1;
    @BindView(R.id.lv_search)
    ListView listView;

    @BindView(R.id.tv_search)
    TextView textView;

    @BindView(R.id.lv_search1)
    PullToRefreshListView listView1;
    private List<PathSearch.TrailsBean> items;
    private MyBaseAdapter<PathSearch.TrailsBean> adapter;
    private int page = 1;

    private String[] names = {"雪山", "梯田", "古道", "草原", "沙漠"};

    private ImageLoader imageLoader;
    private String name;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initViews() {
        super.initViews();

        imageLoader = BaseApplication.getApplication().getImageLoader();

        items = new ArrayList<>();
        name = getIntent().getStringExtra("name");
        if (!TextUtils.isEmpty(name)) {
            linearLayout.setVisibility(View.GONE);
            linearLayout1.setVisibility(View.GONE);
            listView1.setVisibility(View.VISIBLE);
            initListView();
            editText.setText(name);
            loadData1(name);
            return;
        }

        //监听确认按钮
        View.OnKeyListener onKeyListener = new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    linearLayout.setVisibility(View.GONE);
                    linearLayout1.setVisibility(View.GONE);
                    listView1.setVisibility(View.VISIBLE);
                    initListView();
                    editText.setText(editText.getText().toString());
                    loadData1(editText.getText().toString());
                }
                return true;
            }
        };
        editText.setOnKeyListener(onKeyListener);

        //适配gridview 并监听
        gridView.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return names.length;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View inflate = View.inflate(SearchActivity.this, R.layout.adapter_one_textview, null);
                TextView textView = (TextView) inflate.findViewById(R.id.tv_one);

                textView.setText(names[position]);
                return inflate;
            }
        });

        //搜索得到的数据显示适配及监听
        initListView();

        //热门搜索点击事件
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                linearLayout.setVisibility(View.GONE);
                linearLayout1.setVisibility(View.GONE);
                listView1.setVisibility(View.VISIBLE);

                listView1.setMode(PullToRefreshBase.Mode.BOTH);
                loadData1(names[position]);
                editText.setText(names[position]);
            }
        });


        //清除历史搜索记录按钮
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listView.removeAllViews();
            }
        });
    }

    /**
     * 搜索得到的数据显示适配及监听
     */
    private void initListView() {
        adapter = new MyBaseAdapter<PathSearch.TrailsBean>(this, items) {
            @Override
            public int getLayoutId() {
                return R.layout.adapter_path_special_first;
            }

            @Override
            public BaseViewHolder getViewHolder() {
                return new ViewHolder();
            }

            @Override
            public void bindViews(View view, BaseViewHolder viewHolder) {
                ViewHolder holder = (ViewHolder) viewHolder;

                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .cacheOnDisk(true)
                        .cacheInMemory(true)
                        .imageScaleType(ImageScaleType.EXACTLY)
                        .build();
                imageLoader.displayImage(items.get(holder.position).getCover(), holder.imageView, options);

                holder.textView.setText(items.get(holder.position).getName());
                holder.textView1.setText(items.get(holder.position).getDestination());
            }
        };
        listView1.setAdapter(adapter);
        //上拉下拉
        listView1.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                items.clear();
                listView1.setMode(PullToRefreshBase.Mode.BOTH);
                page = 1;
                loadData1(editText.getText().toString());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                loadData1(editText.getText().toString());
            }
        });

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SearchActivity.this, SpecialSecond.class);
                intent.putExtra("id", items.get(position-1).getId());
                intent.putExtra("name", items.get(position-1).getName());
                SearchActivity.this.startActivity(intent);
            }
        });
    }

    /**
     * 数据下载
     *
     */
    protected void loadData1(String name) {
        super.loadData();

        OkHttpUtils.get(Urls.PATH_SEARCH + name + Urls.PATH_SEARCH_END + page, new OkHttpUtils.OnGetDataListener() {
            @Override
            public void onResponse(String url, String data) {
                Gson gson = new Gson();
                PathSearch pathSearch = gson.fromJson(data, PathSearch.class);

                //数据越界
                if (pathSearch.getCur_page() >= pathSearch.getTotal_pages()) {
                    listView1.onRefreshComplete();
                    listView1.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                }
                List<PathSearch.TrailsBean> trails = pathSearch.getTrails();

                items.addAll(trails);
                listView1.onRefreshComplete();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });

    }

    /**
     * 返回
     * @param View
     */
    public void onBack(View View) {
        finish();
    }


    class ViewHolder extends BaseViewHolder {
        @BindView(R.id.iv_path_special_first_adapter)
        ImageView imageView;

        @BindView(R.id.tv_path_special_first_adapter)
        TextView textView;

        @BindView(R.id.tv_path_special_first_adapter1)
        TextView textView1;
    }
}
